<template>
  <j-modal
    switchFullscreen
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" v-if="!disableSubmit">确认</a-button>
    </template>
    <!--    <div class='info-line'>基础设置</div>-->
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item label="用户编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-search placeholder="请选择用户" v-decorator="['userCode', validatorRules.userCode]"
                              readOnly enter-button @search="productSearch('superiorUser')" :disabled="disableSubmit"/>
              <a-input type="hidden" v-decorator="['userCode', validatorRules.userCode]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="用户名称"
              >
              <a-input placeholder="请输入" disabled="true" v-decorator="[ 'userName']"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
              >
              <a-input placeholder="请输入" v-decorator="['remarks']" :disabled="disableSubmit"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <div style="width:90%;margin-left:5%;height: 400px;border: 1px solid #F1F1F1">
      <div>
        <a-button style="margin: 10px 30px 0px 30px;" @click="handleAdd" type="primary" v-if="!disableSubmit">新增
        </a-button>
        <!--        <a-button style="margin: 10px 30px 0px 0px;"type="primary" icon="delete"  @click="">删除</a-button>-->
      </div>
      <div style="padding: 30px">
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :width=900
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{x:400,y:250 }"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
           <a style="color: red;" @click="handleDelete(record)" :disabled="disableSubmit">删除</a>
        </span>
        </a-table>
      </div>
    </div>
    <my-shuttle-modal
      ref="shuttleModal"
      title="选择组织"
      keyVal="orgCode"
      :searchConfig="searchConfig"
      :columns="columnsModal"
      :columns2="columnsModal2"
      leftUrl="/cnOrgController/findTreeList"
      @chooseOk="chooseOk"
    ></my-shuttle-modal>
    <proChose ref="prochoose" v-bind="modalProps" @okbro="okbropro"></proChose>
  </j-modal>
</template>

<script>
import proChose from '@comp/cn-components/ProChose'
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import myShuttleModal from '@/components/cn-components/CnShuttleModal'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'

export default {
  name: 'userorgerlModal',
  data() {
    return {
      name: '',
      sendPro: false,
      remarks: '',
      dataSource: [],
      // dataSurces3: [],
      manobjList: [0],
      recordlist: {},
      areaData: '',
      areaLinkage: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      url: {
        queryById: '/userorgrelation/cnUserOrgRelation/getInfo',
      },
      searchConfig: [
        {
          type: 'input',
          name: 'orgCode',
          placeholder: '组织编号'

        },
        {
          type: 'input',
          name: 'orgName',
          placeholder: '组织名称'
        }

      ],
      /* table选中keys*/
      selectedRowKeys: [],
      columns: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      columnsModal: [

        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        }
      ],
      columnsModal2: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        userCode: {
          rules: [
            { required: true, message: '' }
          ]
        },
        address: {
          rules: [
            { required: true, message: '' }
          ]
        }
      },
      sendOrder: window._CONFIG['domianURL'] + '/material/saveOrUpdate'
    }
  },
  components: { JTreeSelect, JAreaLinkage, UploadImage, JImageUpload, proChose, myShuttleModal },
  created() {

  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    }
  },

  methods: {
    okbropro(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      console.log('弹出框数据', objs)
      this.form.setFieldsValue({
        // parentUserName: objs.userName,
        // parentRealName: objs.realName
        userCode: objs.userName,
        userName: objs.realName
      })
    },
    handleAdd() {
      this.$refs.shuttleModal.visible = true
      this.$refs.shuttleModal.handleSelect()
      this.dataSource.forEach(item => {
        this.$refs.shuttleModal.selectionRows.push({ orgName: item.orgName, orgCode: item.orgCode })
      })
      this.$refs.shuttleModal.loadData()

    },
    add() {
      this.edit()
    },
    edit(isEdit) {
      let that = this
      this.model = {}
      this.dataSource = []
      this.visible = true
      this.form.resetFields()
      if (isEdit) {
        getAction(this.url.queryById, { id: isEdit.id }).then((res) => {
          if (res.success) {
            let record = res.result
            this.dataSource = res.result.cnOrgs
            this.model = Object.assign({}, record)
            let fieldsVal = pick(this.model, 'userCode', 'userName', 'businessType', 'remarks', 'cnOrgs')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldsVal)
              //时间格式化
            })
          }
        })
      }
    },

    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.confirmLoading = false
      this.dataSource = []
      this.model = {}
    },
    handleOk() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(that.model, values)
          formData.cnOrgs = this.dataSource
          // formData.cnOrgs[0]["departCode"]= formData.cnOrgs[0].orgCode
          // formData.cnOrgs[0]["departName"]= formData.cnOrgs[0].orgName
          // delete formData.cnOrgs[0].orgCode;
          // delete formData.cnOrgs[0].orgName;
          console.log('数据', formData)
          postAction('/userorgrelation/cnUserOrgRelation/saveOrUpdate', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message, 2)
              that.$emit('ok')
              that.handleCancel()
            } else {
              that.$message.error(res.message, 2)
            }
          }).finally(() => {
            that.confirmLoading = false
          })

        }
      })
    },
    chooseOk(e) {
      if (this.recordlist ? this.recordlist.cnOrgs : false) {
        this.recordlist.cnOrgs.forEach(item => {
          //   if(item.orgCode){
          //
          // }
        })
      }
      let key = this.dataSource.map(item => item.orgCode)
      e.forEach(item => {
        if (key.indexOf(item.orgCode) == -1) {
          this.dataSource.push(item)
        }
      })
      this.dataSource.forEach(item => {
        Object.defineProperty()
      })
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      if (this.ipagination.current !== pagination.current) {
        this.selectionRows = []
        this.selectedRowKeys = []
      }
      this.ipagination = pagination
      // this.loadData()
    },
    handleDelete(e) {
      let key = this.dataSource.map(item => {
        return item.id
      })
      this.dataSource.splice(key.indexOf(e.id), 1)
    },
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      let formconfig = [
        {
          key: 'userName',
          label: '用户编号'
        },
        {
          key: 'realName',
          label: '用户名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '用户编号',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          },
          {
            title: '用户名称',
            align: 'left',
            dataIndex: 'realName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnUserController/getPageList',
        multiple: false,
        columW: 10
      }

      this.$refs.prochoose.name = '内部用户'
      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          userName: this.form.getFieldValue('superiorUser'),
          realName: this.form.getFieldValue('realsname')
        }]
      }
      console.log(dataSource)
      this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
    }
  }
}
</script>

<style lang="less" scoped>
.info-line {
  display: flex;
  flex-direction: row;
}

.info-line:before {
  content: "";
  flex: 0.1;
  border-bottom: 1px solid #ebedee;
  margin: auto 4px;
}

.info-line:after {
  content: "";
  flex: 0.9;
  border-bottom: 2px solid #ebedee;
  margin: auto 4px;
}
</style>